import json
import os
import socket
import time
import requests
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler, FileSystemEvent
import ssl
import cups


class PrintOnFileCreateHandler(FileSystemEventHandler):
    def __init__(self, cups_server,printer_name,watch_folder, file_extension='.pdf'):
        self.cups_server = cups_server
        self.printer_name =printer_name
        self.watch_folder = watch_folder
        self.file_extension = file_extension

    def on_created(self, event):
        if not event.is_directory and event.src_path.endswith(self.file_extension):
            print(f"find file:{event.src_path}")
            self.print_file(event.src_path)
            os.remove(event.src_path)  #完成后删除

    def print_file(self, file_path):
        file_data = open(file_path, 'rb')
        ipp_job_attributes = {
            'operation-attributes-tag': {
                'requesting-user-name': 'test',
                'job-name': 'Test Job',
                'copies': 1,
                # ... 其他 IPP 属性
            },
            'job-attributes-tag': {
                # ... 其他作业相关的属性
            },
            'data': ('tes.pdf', file_data, 'application/octet-stream')  # 假设你要打印的文件是 PDF
        }

        # IPP 打印作业的 URL（需要根据你的 PAPPL 服务器来配置）
        ipp_url = 'http://192.168.50.70:8000/test'  # 假设 'test' 是打印机的名字
        try:
            response = requests.post(ipp_url, files=ipp_job_attributes)
            response.raise_for_status()  # 如果请求失败，会抛出异常
            print("打印作业已提交")
        except requests.exceptions.RequestException as e:
            print(f"发送打印作业时发生错误: {e}")



event_handler = PrintOnFileCreateHandler(cups_server='192.168.50.70',printer_name='test',watch_folder=r'D:\test')
observer = Observer()
observer.schedule(event_handler, event_handler.watch_folder, recursive=False)

observer.start()
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()

observer.join()
